from django.conf import settings
from django.utils import simplejson as json
from django.http import HttpResponse

from google.appengine.api import memcache

from .utils import (
    get_spreadsheet_list,
    get_entry_with_title,
    get_entry_with_key,
    get_content_url_from_entry,
    get_list_feed_url_from_worksheets_feed,
    get_cell_content_from_list_feed_url,
    cell_content_xml_to_list_of_rows
    )

from google_api_oauth.decorators import oauth_required
from google_api_oauth.views import oauth_logout, clear_oauth_session

from .models import Translator

import logging

@oauth_required('oauth-redirect', ['get_translations'])
def get_translations(request, *args, **kwargs):
    """View for getting translations with sushi_and_tears"""
    access_token = request.session.get('credentials').access_token
    try:
        documents = get_spreadsheet_list(access_token)
    except Exception, e:
        logging.exception(e)
        return oauth_logout(request, 'get_translations')

    entry = False

    if hasattr(settings, "TRANSLATION_SPREADSHEET_TITLE"):
        spreadsheet_title = settings.TRANSLATION_SPREADSHEET_TITLE
        entry = get_entry_with_title(documents, spreadsheet_title)

    if hasattr(settings, "TRANSLATION_SPREADSHEET_KEY"):
        spreadsheet_key = settings.TRANSLATION_SPREADSHEET_KEY
        entry = get_entry_with_key(documents, spreadsheet_key)

    if hasattr(settings, "TRANSLATION_SPREADSHEET_SHEET_NAME"):
        spreadsheet_sheet_name = settings.TRANSLATION_SPREADSHEET_SHEET_NAME
    else:
        spreadsheet_sheet_name = "Sheet1"

    if not entry:
        raise ValueError("No TRANSLATION_SPREADSHEET_TITLE or TRANSLATION_SPREADSHEET_KEY in settings.py")

    worksheet_feed_url = get_content_url_from_entry(entry)
    list_feed_url = get_list_feed_url_from_worksheets_feed(access_token, worksheet_feed_url, spreadsheet_sheet_name)
    content_xml = get_cell_content_from_list_feed_url(access_token, list_feed_url)

    row_list = cell_content_xml_to_list_of_rows(content_xml)


    #TODO: add a method to utils that outputs a dict of key-value pairs per language and get rid of this
    #Delete any existing Translator objects
    flush_translators()

    for language in set(dict(settings.LANGUAGES).keys()):
        content_dict = {}
        for row in row_list:
            for item in row[1:]:
                lang = item[0]
                value = item[1]
                key = item[2]
                if lang == language:
                    content_dict.update({key: value})
                    #Delete cached version
                    memcache.delete("%s%s" % (language, key))

        t = Translator(
            language=language,
            content=json.dumps(content_dict)
        )
        t.save()
        #Flush memcache
        memcache.delete('translator_%s' % language)

    #We're done so clear the OAuth session
    clear_oauth_session(request)

    return HttpResponse('Finished getting translations')

def flush_translators():
    """ Remove all existing Translator objects """
    translators = Translator.objects.all()
    for translator in translators:
        translator.delete()
